package com.mixoft.TestApp;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.util.SparseArray;

public class BaseFragmentPagerAdapter extends FragmentPagerAdapter {
	
	public static final String TAG = "BaseFragmentPagerAdapter";
	
	// Internal value to hold the layouts we can switch through
	// and their respective titles
	private SparseArray<Fragment> inflatedLayouts;
	private String[] pagerTitles;
	
	public BaseFragmentPagerAdapter(int[] layouts, String[] titles, FragmentManager manager)
	{
		// Call base constructor
		super(manager);
	
		Log.d(TAG, "Fragment pager adapter is initialized");
		
		// Inflate the layouts we got and store them in a sparsearray
		this.inflatedLayouts = new SparseArray<Fragment>();
		for (int i = 0; i < layouts.length; i++)
		{
			GenericFragmentInflator frag = new GenericFragmentInflator();
			frag.setPage(layouts[i]);
			this.inflatedLayouts.put(i, frag);			
		}
		
		// Set the titles to what we got from caller
		this.pagerTitles = titles;
	}
	
	/*
	 * Returns the count of layouts we can switch through (non-Javadoc)
	 * @see android.support.v4.view.PagerAdapter#getCount()
	 */
    public int getCount() {
        return this.inflatedLayouts.size();
    }
    
    /*
     * Returns the corresponding title of a page by it's position
     */
    @Override
    public String getPageTitle(int position) {
        return this.pagerTitles[position % this.pagerTitles.length];
    }
    
    /*
     * Creates a generic class with the resource ID of the requested page
     * The generic class is the one who inflates the resource when requested (non-Javadoc)
     * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
     */
	@Override
	public Fragment getItem(int position) {
		Log.d(TAG, "Recieved getItem call for position=" + position);
		
		return this.inflatedLayouts.get(position % this.getCount());
	}
}
